package org.rency.ues.domainservice.crypto.support;

import java.util.concurrent.ConcurrentHashMap;

import org.rency.ues.common.enums.EncryptType;
import org.rency.ues.domainservice.crypto.Cryptor;
import org.rency.ues.domainservice.crypto.Decryptor;
import org.rency.ues.domainservice.crypto.Encryptor;

public class CryptoFactory {

	public static ConcurrentHashMap<String,Cryptor> cachedCryptors=new ConcurrentHashMap<String, Cryptor>();
	public static Cryptor createCryptor(EncryptType type){
		return createCryptor(type,true);
	}
	public static Encryptor createEncryptor(EncryptType type){
		return createCryptor(type,true);
	}
	public static Decryptor createDecryptor(EncryptType type){
		return createCryptor(type,true);
	}
	public static Encryptor createEncryptor(EncryptType type,boolean ifPossibleFromCache){
		return createCryptor(type,ifPossibleFromCache);
	}
	public static Decryptor createDecryptor(EncryptType type,boolean ifPossibleFromCache){
		return createCryptor(type,ifPossibleFromCache);
	}
	public static Cryptor createCryptor(EncryptType type,boolean ifPossibleFromCache){
		if(type==null){
			throw new NullPointerException("NullPointerException: type is null.");
		}
		Cryptor c=null;
		if(ifPossibleFromCache){
			c=cachedCryptors.get(type.toString());
			if(c==null){
				c=createNewCryptor(type);
				if(c!=null)
					cachedCryptors.put(type.toString(), c);
			}
		}else{
			c=createNewCryptor(type);
		}
		return c;
	}

	private static Cryptor createNewCryptor(EncryptType type){
		Cryptor c=null;
		switch(type){
		case CMS:
			c=new CMSRSACryptor(type);
			break;
		case RSA:
			c= new RSACryptor(type);
			break;
		case DES:
			c=new DESCryptor(type);
			break;
		default:
			throw new UnsupportedOperationException("Unsupported exception. not support type["+type+"].");
		}
		return c;
	}
	
}